<template>
  <div>
    <el-card style="width: 100%">
      <div class="warppar">
        <div class="warppar-left">
          <div class="col-md-5">
            <blockquote>
              <p>插件有什么用？</p>
              <small class="text-muted">插件是一种可扩展全量同步和增量同步实现数据转换的技术方式。通过插件可以接收同步数据，自定义同步到目标源的行数据，也能消费数据并实现更多业务场景。</small>
            </blockquote>

            <p>如何开发插件？</p>
            <ol>
              <li>
                新建java或maven工程，或者下载
                <a href="https://gitee.com/ghi/dbsyncer-plugin-demo" title="提供开发者编写插件的示例项目" target="_blank">示例项目</a>
              </li>
              <li>
                导入开发包：
                <ul>
                  <li>
                    方式1：导入jar
                    <p>
                      <a onclick="downLoad('sdk')" href="javascript:;" title="下载开发包">dbsyncer-sdk-1.0.0-Release.jar</a>
                    </p>
                  </li>
                  <li>
                    方式2：引入pom（需要安装到本地）
                    <pre>&lt;dependency&gt;<br>&nbsp;&nbsp;&lt;groupId&gt;org.ghi&lt;/groupId&gt;<br>&nbsp;&nbsp;&lt;artifactId&gt;dbsyncer-sdk&lt;/artifactId&gt;<br>&nbsp;&nbsp;&lt;version&gt;1.0.0-Release&lt;/version&gt;<br>&lt;/dependency&gt;</pre>
                  </li>
                </ul>
              </li>
              <li>
                <div>新建一个类，比如MyPlugin，实现接口PluginService方法</div>
                <pre>
package org.test;

import org.dbsyncer.sdk.connector.ConnectorInstance;
import org.dbsyncer.sdk.connector.database.DatabaseConnectorInstance;
import org.dbsyncer.sdk.connector.database.ds.SimpleConnection;
import org.dbsyncer.sdk.plugin.PluginContext;
import org.dbsyncer.sdk.spi.PluginService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class MyPlugin implements PluginService {

    private final Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * 全量同步/增量同步
     *
     * @param convertContext
     */
    @Override
    public void convert(PluginContext pluginContext) {
        // TODO 消费或处理数据
        System.out.println("插件消费数据中...");

        // 是否终止同步到目标库开关，默认false
        pluginContext.setTerminated(false);

        // 数据源表和目标源表
        pluginContext.getSourceTableName();
        pluginContext.getTargetTableName();

        // 捕获的事件（INSERT/UPDATE/DELETE）
        pluginContext.getEvent();

        // 数据源和目标源表全量或增量数据
        pluginContext.getSourceList();
        pluginContext.getTargetList();

        // 获取目标库连接器实例（如果需要用到连接器，必须引入dbsyncer-connector-1.0.0-Release.jar）
        pluginContext.getTargetConnectorInstance();
    }

    /**
     * 全量同步/增量同步完成后执行处理
     *
     * @param context
     */
    @Override
    public void postProcessAfter(PluginContext context) {
        // 完成同步后调用该方法
       logger.info("插件正在处理同步成功的数据，目标源表:{}，事件:{}，条数:{}", context.getTargetTableName(), context.getEvent(), context.getTargetList().size());

        ConnectorInstance connectorInstance = context.getSourceConnectorInstance();

        // 获取关系型数据库连接，实现自己的业务逻辑...
        if (connectorInstance instanceof DatabaseConnectorInstance) {
            DatabaseConnectorInstance db = (DatabaseConnectorInstance) connectorInstance;
            // 方式一（推荐）：
            String query = "select * from my_user";
            db.execute(databaseTemplate -&gt; databaseTemplate.queryForList(query));

            // 方式二：
            SimpleConnection connection = null;
            try {
                // 通过JDBC访问数据库
                connection = (SimpleConnection) db.getConnection();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if(connection != null){
                    connection.close();
                }
            }
        }
    }

    /**
     * 重写方法：设置版本号
     *
     * @return
     */
    @Override
    public String getVersion() {
        return "1.0.0";
    }

    /**
     * 重写方法：设置插件名称
     *
     * @return
     */
    @Override
    public String getName() {
        return "我的插件";
    }
}</pre>
              </li>
              <li>
                <div>
                  /META-INF/新建services文件夹，并在services下新建一个文件，命名为org.dbsyncer.common.spi.ConvertService，文件写入实现类路径org.test.MyPlugin，如果有多个实现就换行再写入
                </div>
                <p>
                  <img draggable="false" src="../../assets/plugIn/spi.png" />
                </p>
              </li>
              <li>
                <div>打包jar</div>
                <p>
                  <img draggable="false" src="../../assets/plugIn/jar.png" />
                </p>
              </li>
            </ol>
          </div>
        </div>
        <div class="warppar-right">
          <el-upload class="upload-demo" drag ref="el-upload" action="#" :show-file-list="true" :auto-upload="false"
            :http-request="handleUpload" accept=".jar" multiple>
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">
              将文件拖到此处，或<em>点击上传</em>
            </div>
            <div class="el-upload__tip" slot="tip">
              <div class="el-upload__tip" slot="tip">
                <h1 style="display: inline-block">上传配置</h1>
                <h3 style="display: inline-block; margin-left: 8px">
                  只支持 "jar" 的文件扩展名.

                  <el-button size="small" @click="handleClickUpload" type="primary">立即上传</el-button>
                </h3>
              </div>
            </div>
          </el-upload>


          <el-table v-loading="loading" :data="postList">
            <el-table-column show-overflow-tooltip label="名称" min-width="50" align="center" prop="name" />
            <el-table-column show-overflow-tooltip label="运行驱动" min-width="50" align="center" prop="phone" />
            <el-table-column show-overflow-tooltip label="类名" min-width="50" align="center" prop="mealCardNumber" />
            <el-table-column show-overflow-tooltip label="版本" min-width="50" align="center" prop="mealCardNumber" />
            <el-table-column show-overflow-tooltip label="文件" min-width="50" align="center" prop="mealCardNumber" />
          </el-table>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script>
import { uploadPlugin } from "@/api/plugIn/index";
export default {
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 岗位表格数据
      postList: [],
      // 弹出层标题
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        thirdOrderId: "",
        phone: "",
        couponTypeEnum: "",
        mealCardNumber: "",
      },
    };
  },
  created() {
    this.getList();
  },
  methods: {
    async getList() {

    },
    handleClickUpload() {
      this.$refs['el-upload'].submit();
      // setTimeout(() => {
      //   this.$refs['el-upload'].clearFiles();
      // }, 2000);
    },
    /** 上传文件 */
    handleUpload(options) {
      console.log(options);
      let formdata = new FormData();
      formdata.append('files', options.file);
      formdata.append('fileId', options.file.name);
      formdata.append('initialPreview', '[]');
      formdata.append('initialPreviewConfig', '[]');
      formdata.append('initialPreviewThumbTags', '[]');

      options.onProgress = e=>{
        console.log("上传进度：",e)
      }
      return uploadPlugin(formdata);

    }
  },
};
</script>
<style lang="scss" scoped>
.warppar {
  display: flex;
  flex-wrap: wrap;

  .warppar-left {
    width: 60%;
    margin-right: 20px;
    margin-bottom: 20px;
  }

  .warppar-right {
    width: 460px;
    margin-right: 20px;
  }
}

@media screen and (max-width: 1110px) {
  .warppar .warppar-left {
    width: 100%;
  }
}

pre {
  display: block;
  padding: 9.5px;
  margin: 0 0 10px;
  font-size: 13px;
  line-height: 1.42857143;
  color: #333;
  word-break: break-all;
  word-wrap: break-word;
  background-color: #f5f5f5;
  border: 1px solid #ccc;
  border-radius: 4px;
  overflow: auto;
}

blockquote {
  padding: 10px 20px;
  margin: 0 0 20px;
  font-size: 17.5px;
  border-left: 5px solid #eee;
}
</style>
